package test.web;

import app.AppMain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import test.constant.AppTestConstants;

import javax.servlet.DispatcherType;
import java.io.File;
import java.util.EnumSet;

/**
 * @author mh.z
 */
public class AppTestWeb {
    private static final String SPRING_CONTEXT_CONFIG_LOCATION =
            "classpath:/jasmine/framework/test/config/springContext.xml";
    private static final String SYSTEM_PROP_USER_DIR = "user.dir";
    private static final String DEFAULT_CUSTOM_CONFIG_FILE_NAME = "local-dev.properties";

    public static void main(String[] args) throws Exception {
        // 初始系统参数
        initSystemProperties();
        // 设置 Jetty 日志级别
        StdErrLog logger = new StdErrLog();
        logger.setLevel(StdErrLog.LEVEL_INFO);
        Log.setLog(logger);

        Server server = new Server(AppTestConstants.PORT);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath(AppTestConstants.CONTEXT_PATH);
        server.setHandler(context);

        // SpringMVC 请求入口
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        ServletHolder servletHolder = new ServletHolder();
        dispatcherServlet.setContextConfigLocation(SPRING_CONTEXT_CONFIG_LOCATION);
        servletHolder.setServlet(dispatcherServlet);
        context.addServlet(servletHolder, "/*");

        // 字符编码过滤器
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        encodingFilter.setForceEncoding(true);
        FilterHolder filterHolder = new FilterHolder();
        filterHolder.setFilter(encodingFilter);
        context.addFilter(filterHolder, "/*", EnumSet.of(
                DispatcherType.REQUEST, DispatcherType.FORWARD));

        context.addFilter(AppTestFilter.class, "/*", EnumSet.of(
                DispatcherType.REQUEST, DispatcherType.FORWARD));

        server.start();
        server.join();
    }

    /**
     * 初始系统参数
     *
     * @throws Exception
     */
    protected static void initSystemProperties() throws Exception {
        String customConfigPath = System.getProperty(SYSTEM_PROP_USER_DIR) +
                File.separator + DEFAULT_CUSTOM_CONFIG_FILE_NAME;

        AppMain.initSystemProperties(customConfigPath);
    }

}
